package cn.itsource.basic.util;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件操作的工具类
 */
public class FileUtil {

    /**
     * 文件上传
     *
     * @return
     */
    public static String fileUpload(MultipartFile file) {

        String name = file.getOriginalFilename();

        String suffix = FileNameUtil.getSuffix(name);

        String uuid = IdUtil.fastUUID();

        String objectName = "exampledir/" + uuid + "." + suffix;

        OSS ossClient = new OSSClientBuilder().build(cn.itsource.util.Constants.END_POINT, cn.itsource.util.Constants.accessKeyId, cn.itsource.util.Constants.accessKeySecret);

        try {
            ossClient.putObject(cn.itsource.util.Constants.bucketName, objectName, file.getInputStream());

            return "https://" + cn.itsource.util.Constants.bucketName + ".oss-cn-hangzhou.aliyuncs.com" + "/" + objectName;
        } catch (Exception oe) {
            oe.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
